var express = require('express');
var superagent = require('superagent');
var router = express.Router();
var timeoutTime = 15000;
/* GET home page. */


router.get('/', function(req, res, next) {

  var isPhone = false;
  var agentID = req.headers['user-agent'].toLowerCase().search(/(micromessenger)/);
  if (agentID > 0) {
    isPhone = true;
  }
  else {
    isPhone = false;
  }
  if (global.IO_OAUTH == false) {
    isPhone = false; //暂时屏蔽授权
  }

  res.setTimeout(timeoutTime, function() {
    console.error("响应超时.");
    res.render('timeout', {});
  });
  var openid = req.query.openid || 'null';
  var access_token = req.query.access_token || 'null';

  superagent
    .get('https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN')
    .end(function(err, res4) {
      if (res4.text.indexOf('errcode') > 0 && isPhone) {
        var state = encodeURIComponent(req.url.split('&openid')[0]);

        console.log(' openid为空--------- ');
        superagent
          .get(global.wechatURL + '/wechat_oauth/getAuthorizeURL?state=' + state + '&finalbase=' + global.browserURL)
          .end(function(err, res3) {
            if (res3 !== undefined && res3.ok) {
              res.redirect(res3.text);
              return;
            }
            else {
              console.error('微信授权错误。');
              logger.error('微信授权错误。');
              res.render('error', {});
            }
          });
      }
      else {
        console.log(' 正常请求---------- ');
        var targetType = 20;
        var targetId = global.targetId;
        superagent
          .get(global.baseURL + '/api/comments/?targetType=' + targetType + '&targetId=' + targetId)
          .set({
            'DEVICE': 'weixin',
            'DEVICE_ID': openid
          })
          .end(function(err, res1) {
            if (res1 !== undefined && res1.ok) {
              //--------
              var thisUrl = req.url;

              var shareUrl = encodeURIComponent((global.browserURL + thisUrl).split('#')[0]);
              superagent
                .get(global.wechatURL + '/wechat_api/jsconfig?url=' + shareUrl)
                .end(function(err, res2) {
                  if (res2 !== undefined && res2.ok){
                    res1.body.result.commentInfo = {id:targetId,type:targetType};
                    res1.body.result.browserURL = global.browserURL;
                    res1.body.result.wxConfig = res2.body;
                    res1.body.result.userInfo = JSON.parse(res4.text);
                    res.render('index', res1.body.result);
                  }
                  else {
                    console.error('微信分享api错误。');
                    logger.error('微信分享api错误。');
                    res.render('error', {});
                  }
                });
              //--------
            }
            else {
              console.error('请求数据错误!');
              logger.error('请求数据错误。');
              res.render('error', {});
            }
          });
      }
    });

});

router.get('/second', function(req, res, next) {

  var isPhone = false;
  var agentID = req.headers['user-agent'].toLowerCase().search(/(micromessenger)/);
  if (agentID > 0) {
    isPhone = true;
  }
  else {
    isPhone = false;
  }
  if (global.IO_OAUTH == false) {
    isPhone = false; //暂时屏蔽授权
  }

  res.setTimeout(timeoutTime, function() {
    console.error("响应超时.");
    res.render('timeout', {});
  });
  var openid = req.query.openid || 'null';
  var access_token = req.query.access_token || 'null';

  superagent
    .get('https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN')
    .end(function(err, res4) {
      if (res4.text.indexOf('errcode') > 0 && isPhone) {
        var state = encodeURIComponent(req.url.split('&openid')[0]);

        console.log(' openid为空--------- ');
        superagent
          .get(global.wechatURL + '/wechat_oauth/getAuthorizeURL?state=' + state + '&finalbase=' + global.browserURL)
          .end(function(err, res3) {
            if (res3 !== undefined && res3.ok) {
              res.redirect(res3.text);
              return;
            }
            else {
              console.error('微信授权错误。');
              logger.error('微信授权错误。');
              res.render('error', {});
            }
          });
      }
      else {
        console.log(' 正常请求---------- ');
        var targetType = 20;
        var targetId = global.targetId2;
        superagent
          .get(global.baseURL + '/api/comments/?targetType=' + targetType + '&targetId=' + targetId)
          .set({
            'DEVICE': 'weixin',
            'DEVICE_ID': openid
          })
          .end(function(err, res1) {
            if (res1 !== undefined && res1.ok) {
              //--------
              var thisUrl = req.url;

              var shareUrl = encodeURIComponent((global.browserURL + thisUrl).split('#')[0]);
              superagent
                .get(global.wechatURL + '/wechat_api/jsconfig?url=' + shareUrl)
                .end(function(err, res2) {
                  if (res2 !== undefined && res2.ok){
                    res1.body.result.commentInfo = {id:targetId,type:targetType};
                    res1.body.result.browserURL = global.browserURL;
                    res1.body.result.wxConfig = res2.body;
                    res1.body.result.userInfo = JSON.parse(res4.text);
                    res.render('second', res1.body.result);
                  }
                  else {
                    console.error('微信分享api错误。');
                    logger.error('微信分享api错误。');
                    res.render('error', {});
                  }
                });
              //--------
            }
            else {
              console.error('请求数据错误!');
              logger.error('请求数据错误。');
              res.render('error', {});
            }
          });
      }
    });

});

router.get('/third', function(req, res, next) {

  var isPhone = false;
  var agentID = req.headers['user-agent'].toLowerCase().search(/(micromessenger)/);
  if (agentID > 0) {
    isPhone = true;
  }
  else {
    isPhone = false;
  }
  if (global.IO_OAUTH == false) {
    isPhone = false; //暂时屏蔽授权
  }

  res.setTimeout(timeoutTime, function() {
    console.error("响应超时.");
    res.render('timeout', {});
  });
  var openid = req.query.openid || 'null';
  var access_token = req.query.access_token || 'null';

  superagent
    .get('https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN')
    .end(function(err, res4) {
      if (res4.text.indexOf('errcode') > 0 && isPhone) {
        var state = encodeURIComponent(req.url.split('&openid')[0]);

        console.log(' openid为空--------- ');
        superagent
          .get(global.wechatURL + '/wechat_oauth/getAuthorizeURL?state=' + state + '&finalbase=' + global.browserURL)
          .end(function(err, res3) {
            if (res3 !== undefined && res3.ok) {
              res.redirect(res3.text);
              return;
            }
            else {
              console.error('微信授权错误。');
              logger.error('微信授权错误。');
              res.render('error', {});
            }
          });
      }
      else {
        console.log(' 正常请求---------- ');
        var targetType = 20;
        var targetId = global.targetId3;
        superagent
          .get(global.baseURL + '/api/comments/?targetType=' + targetType + '&targetId=' + targetId)
          .set({
            'DEVICE': 'weixin',
            'DEVICE_ID': openid
          })
          .end(function(err, res1) {
            if (res1 !== undefined && res1.ok) {
              //--------
              var thisUrl = req.url;

              var shareUrl = encodeURIComponent((global.browserURL + thisUrl).split('#')[0]);
              superagent
                .get(global.wechatURL + '/wechat_api/jsconfig?url=' + shareUrl)
                .end(function(err, res2) {
                  if (res2 !== undefined && res2.ok){
                    res1.body.result.commentInfo = {id:targetId,type:targetType};
                    res1.body.result.browserURL = global.browserURL;
                    res1.body.result.wxConfig = res2.body;
                    res1.body.result.userInfo = JSON.parse(res4.text);
                    res.render('third', res1.body.result);
                  }
                  else {
                    console.error('微信分享api错误。');
                    logger.error('微信分享api错误。');
                    res.render('error', {});
                  }
                });
              //--------
            }
            else {
              console.error('请求数据错误!');
              logger.error('请求数据错误。');
              res.render('error', {});
            }
          });
      }
    });
});

router.get('/show',function (req,res,next) {
  var isPhone = false;
  var agentID = req.headers['user-agent'].toLowerCase().search(/(micromessenger)/);
  if (agentID > 0) {
    isPhone = true;
  }
  else {
    isPhone = false;
  }
  if (global.IO_OAUTH == false) {
    isPhone = false; //暂时屏蔽授权
  }

  res.setTimeout(timeoutTime, function() {
    console.error("响应超时.");
    res.render('timeout', {});
  });
  var openid = req.query.openid || 'null';
  var access_token = req.query.access_token || 'null';

  superagent
    .get('https://api.weixin.qq.com/sns/userinfo?access_token=' + access_token + '&openid=' + openid + '&lang=zh_CN')
    .end(function(err, res4) {
      if (res4.text.indexOf('errcode') > 0 && isPhone) {
        var state = encodeURIComponent(req.url.split('&openid')[0]);
        console.log(state);
        console.log(' openid为空--------- ');
        superagent
          .get(global.wechatURL + '/wechat_oauth/getAuthorizeURL?state=' + state + '&finalbase=' + global.browserURL)
          .end(function(err, res3) {
            if (res3 !== undefined && res3.ok) {
              res.redirect(res3.text);
              return;
            }
            else {
              console.error('微信授权错误。');
              logger.error('微信授权错误。');
              res.render('error', {});
            }
          });
      }
      else {
        console.log(' 正常请求---------- ');
        var targetType = 20;
        var targetId = global.targetId;
        var thisUrl = req.url;
        var shareUrl = encodeURIComponent((global.browserURL + thisUrl).split('#')[0]);
        superagent
          .get(global.wechatURL + '/wechat_api/jsconfig?url=' + shareUrl)
          .end(function(err, res2) {
            var info = {};
            if (res2 !== undefined && res2.ok){
              info.browserURL = global.browserURL;
              info.wxConfig = res2.body;
              info.userInfo = res4.text;
              res.render('show',info);
            }
            else {
              console.error('微信分享api错误。');
              logger.error('微信分享api错误。');
              res.render('error', {});
            }
          });
        }
    });
})

router.get('/tv',function(req,res,next){
  var id = req.query.id;
  console.log(id);
  var num = id - 1;

  res.setTimeout(timeoutTime, function() {
    console.error("响应超时.");
    res.render('timeout', {});
  });

  var openid = req.query.openid || 'null';
  var access_token = req.query.access_token || 'null';

  var targetType = 20;
  var targetId = global.targetIdArray[num];
  superagent
    .get(global.baseURL + '/api/comments/?targetType=' + targetType + '&targetId=' + targetId)
    .set({
      'DEVICE': 'weixin',
      'DEVICE_ID': openid
    })
    .end(function(err, res1) {
      if (res1 !== undefined && res1.ok) {
        //--------
        var thisUrl = req.url;
        var shareUrl = encodeURIComponent((global.browserURL + thisUrl).split('#')[0]);
        superagent
          .get(global.wechatURL + '/wechat_api/jsconfig?url=' + shareUrl)
          .end(function(err, res2) {
            if (res2 !== undefined && res2.ok){
              res1.body.result.id  = id;
              res1.body.result.commentInfo = {id:targetId,type:targetType};
              res1.body.result.browserURL = global.browserURL;
              res1.body.result.wxConfig = res2.body;
              res.render('tv', res1.body.result);
            }
            else {
              console.error('微信分享api错误。');
              logger.error('微信分享api错误。');
              res.render('error', {});
            }
          });
        //--------
      }
      else {
        console.error('请求数据错误!');
        logger.error('请求数据错误。');
        res.render('error', {});
      }
    });
})

router.get('/test',function(req,res,next){
  res.render('test');          
})


module.exports = router;
